﻿using Learun.Application.Base.AuthorizeModule;
using Learun.Application.Organization;
using Learun.Application.TwoDevelopment.ZZDT_EC;
using Learun.Util;
using Learun.Util.Operat;
using Learun.Util.SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace Learun.Application.Web.Areas.ZZDT_EC.Controllers
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2020-12-04 15:20
    /// 描 述：项目管理
    /// </summary>
    public class ec_projectController : MvcControllerBase
    {
        private ec_projectIBLL ec_projectIBLL = new ec_projectBLL();

        #region 视图功能

        /// <summary>
        /// 主页面
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 项目切换页面
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ProjectListIndex()
        {
            return View();
        }

        /// <summary>
        /// 表单页
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Form()
        {
            return View();
        }

        /// <summary>
        /// 项目选择界面
        /// </summary>
        /// <returns></returns>
        public ActionResult SelectProjectForm()
        {
            return View();
        }

        #endregion

        #region 获取数据

        /// <summary>
        /// 获取页面显示列表数据
        /// <summary>
        /// <param name="queryJson">查询参数</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetPageList(string pagination, string queryJson)
        {
            Pagination paginationobj = pagination.ToObject<Pagination>();
            var data = ec_projectIBLL.GetList(queryJson, paginationobj);
            var jsonData = new
            {
                rows = data,
                total = paginationobj.total,
                page = paginationobj.page,
                records = paginationobj.records
            };
            return Success(jsonData);
        }

        /// <summary>
        /// 获取项目选择页面显示列表数据
        /// <summary>
        /// <param name="queryJson">查询参数</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetProjectSelectPageList(string pagination, string queryJson)
        {
            Pagination paginationobj = pagination.ToObject<Pagination>();
            var data = ec_projectIBLL.GetProjectSelectPageList(paginationobj, queryJson);
            var jsonData = new
            {
                rows = data,
                total = paginationobj.total,
                page = paginationobj.page,
                records = paginationobj.records
            };
            return Success(jsonData);
        }

        /// <summary>
        /// 获取项目下拉框
        /// </summary>
        /// <param name="queryJson"></param>
        /// <returns></returns>
        public ActionResult GetProjectSelectList(string queryJson)
        {
            Pagination paginationobj = new Pagination();
            paginationobj.page = 1;
            paginationobj.rows = 10000;
            paginationobj.sidx = "CreateTime";
            paginationobj.sord = "DESC";
            var data = ec_projectIBLL.GetProjectSelectPageList(paginationobj, queryJson);
            return Success(data);
        }

        /// <summary>
        /// 根据id获取项目数据
        /// <summary>
        /// <param name="queryJson">查询参数</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetProjectById(string ProjectId)
        {
            var ec_projectData = ec_projectIBLL.GetEntity(ProjectId);
            var jsonData = new
            {
                ec_project = ec_projectData,
            };
            return Success(jsonData);
        }

        /// <summary>
        /// 获取表单数据
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetFormData(string keyValue)
        {
            var ec_projectData = ec_projectIBLL.GetEntity(keyValue);
            var jsonData = new
            {
                ec_project = ec_projectData,
            };
            return Success(jsonData);
        }
        #endregion

        #region 提交数据

        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult DeleteForm(string keyValue, string projectIndex)
        {
            ec_projectIBLL.DeleteEntity(keyValue, Convert.ToInt32(projectIndex));
            return Success("删除成功！", "项目列表", OperationType.Delete, null, null);
        }

        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult SaveForm(string keyValue, string strEntity)
        {
            ec_projectEntity entity = strEntity.ToObject<ec_projectEntity>();
            //新建、编辑项目时，项目名称、项目编号不允许重复。
            var data = ec_projectIBLL.GetList("{}").ToList();
            data = data.FindAll(x => x.ProjectName == entity.ProjectName || x.ProjectCode == entity.ProjectCode);
            if (data != null && data.Count > 0)
            {
                if (!string.IsNullOrEmpty(keyValue))
                {
                    data = data.FindAll(x => x.ProjectId != keyValue);
                    if (data != null && data.Count > 0)
                    {
                        return Fail("项目名称或项目编号重复！");
                    }
                }
                else
                {
                    return Fail("项目名称或项目编号重复！");
                }
            }
            ec_projectIBLL.SaveEntity(keyValue, entity);
            if (string.IsNullOrEmpty(keyValue))
            {
                entity = ec_projectIBLL.GetEntity(entity.ProjectId);
                //复制角色
                CopyRole(entity.ProjectId);
                //从业务表中获取数据，复制表结构
                var listBusinessTable = new ec_business_tableBLL().GetList("{}").ToList();
                if (listBusinessTable != null && listBusinessTable.Count > 0)
                {
                    List<string> TableCodes = listBusinessTable.Select(x => x.BusinessTableCode).Distinct().ToList();
                    //新建项目时需要复制“是否复制数据”为1的表数据
                    List<string> CopyTableData = listBusinessTable.FindAll(x => x.IsCopyData == 1).Select(x => x.BusinessTableCode).Distinct().ToList();
                    CopyTableAndData(TableCodes, Convert.ToInt32(entity.ProjectIndex), false, CopyTableData);
                    if (CopyTableData.Exists(x => x == "ec_library_file"))
                    {
                        new ec_library_fileBLL().SaveDataAndAnnexes(entity.ProjectId);
                    }
                    if (CopyTableData.Exists(x => x == "ec_drawing_file"))
                    {
                        new ec_drawing_fileBLL().SaveDataAndAnnexes(entity.ProjectId);
                    }
                    if (CopyTableData.Exists(x => x == "ec_template_file"))
                    {
                        new ec_template_fileBLL().SaveDataAndAnnexes(entity.ProjectId);
                    }
                    if (CopyTableData.Exists(x => x == "ec_report_file"))
                    {
                        new ec_report_fileBLL().SaveDataAndAnnexes(entity.ProjectId);
                    }
                }
            }
            return Success("保存成功！", "项目列表", string.IsNullOrEmpty(keyValue) ? OperationType.Create : OperationType.Update, null, null);
        }

        /// <summary>
        /// 从单位平台同步对数据到项目表中
        /// <param name="projectCode">项目编号</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult SynData(string ProjectIndex, string strData, string ProjectId)
        {
            //判断是否有工程数据
            int countenginedata = new ec_enginedataBLL().GetDataCount(ProjectId);
            if (countenginedata > 0)
            {
                return Fail("该项目已经存在设计数据，不允许同步数据！");
            }
            //页面上勾选的需要同步的表编号
            List<string> listTableCode = strData.ToList<string>();
            //同步关联表数据
            var synrelTable = new ec_synrel_tableBLL().GetList("{}").ToList();
            //需要同步表编号
            List<string> synTableCodes = new List<string>();
            foreach (var item in listTableCode)
            {
                var allDataByCode = synrelTable.FindAll(x => x.MainBusinessTableCode == item).Select(x => x.RelBusinessTableCode);
                synTableCodes.AddRange(allDataByCode);
            }
            //最后需要同步数据的表编号集合
            var copyTables = listTableCode.Union(synTableCodes).Distinct().ToList();
            CopyTableAndData(copyTables, Convert.ToInt32(ProjectIndex), true, new List<string>());
            if (copyTables.Exists(x => x == "ec_library_file"))
            {
                new ec_library_fileBLL().SaveDataAndAnnexes(ProjectId);
            }
            if (copyTables.Exists(x => x == "ec_drawing_file"))
            {
                new ec_drawing_fileBLL().SaveDataAndAnnexes(ProjectId);
            }
            if (copyTables.Exists(x => x == "ec_template_file"))
            {
                new ec_template_fileBLL().SaveDataAndAnnexes(ProjectId);
            }
            if (copyTables.Exists(x => x == "ec_report_file"))
            {
                new ec_report_fileBLL().SaveDataAndAnnexes(ProjectId);
            }
            return Success("同步成功！");
        }

        #endregion

        /// <summary>
        /// 复制角色
        /// </summary>
        /// <param name="ProjectId">项目ID</param>
        private void CopyRole(string ProjectId)
        {
            RoleBLL roleBLL = new RoleBLL();
            UserRelationIBLL userRelationIBLL = new UserRelationBLL();

            List<RoleEntity> projRoleList = roleBLL.GetList(ProjectId);
            if (projRoleList == null || projRoleList.Count == 0)
            {
                UserInfo userInfo = LoginUserInfo.Get();
                List<RoleEntity> commonRoleList = roleBLL.GetList("00000000-0000-0000-0000-000000000001");//单位通用的项目角色
                foreach (RoleEntity roleEntity in commonRoleList)
                {
                    IEnumerable<UserRelationEntity> commonUserRelationEntity = userRelationIBLL.GetUserIdList(roleEntity.F_RoleId, "00000000-0000-0000-0000-000000000001");
                    //拷贝授权
                    var auths = SqlSugarHelper.Db.Queryable<AuthorizeEntity>().Where(x => x.F_ObjectId == roleEntity.F_RoleId).ToList();

                    RoleEntity newRoleEntity = roleEntity;
                    newRoleEntity.ProjectId = ProjectId;
                    roleBLL.SaveEntity("", ref newRoleEntity);

                    foreach (UserRelationEntity userRelationEntity in commonUserRelationEntity)
                    {
                        UserRelationEntity newUserRelationEntity = userRelationEntity;
                        newUserRelationEntity.F_ObjectId = newRoleEntity.F_RoleId;
                        newUserRelationEntity.ProjectId = ProjectId;
                        userRelationIBLL.SaveEntity("", newUserRelationEntity);
                    }

                    auths.ForEach(x =>
                    {
                        x.Create();
                        x.F_ObjectId = newRoleEntity.F_RoleId;
                    });
                    SqlSugarHelper.Db.Insertable(auths).ExecuteCommand();
                }
            }
        }

        /// <summary>
        /// 复制表及数据
        /// </summary>
        /// <param name="projectIndex">项目序号</param>
        /// <param name="listTableName">要复制的表名集合</param>
        /// <param name="isCopyData">是否要复制数据,默认为不复制</param>
        /// <param name="CopyTableData">新建项目时需要复制“是否复制数据”为1的表数据</param>
        private void CopyTableAndData(List<string> listTableName, int projectIndex, bool isCopyData, List<string> CopyTableData)
        {
            ec_projectIBLL.ExecuteSQL(listTableName, projectIndex, isCopyData, CopyTableData);
        }
    }
}
